var menuVersion = "";
window.newVersion="";
var strAdd = "";
var strBeanAdd = "";
$(function(){
	dataInit();
});

function dataInit(){
	eventInit();
	$('#messageTable').bootstrapTable({
        url: path+'408d41b977294903a85e815bb32bbdaa', method: 'post', striped: true, cache: false, pagination: true,
        contentType: "application/x-www-form-urlencoded", sidePagination: "server", pageSize: 10, uniqueId: "id", detailView: false,
        queryParams: function (params) {
        	return { limit: params.limit, offset: params.offset};
        },//传递参数（*）
        columns:[{field: 'Number', title: '序号', align: 'center', width: '80', formatter: function (value, row, index) {
        			return index+1;
        		}}, 
        		{field: 'menuName', title: '菜单名称', align: 'center', width: '150', formatter: function (value, row, index) {
	            	return '<a style="word-wrap:break-word;">'+value+'</a>';
	            }},
        		{field: 'name', title: '创建人', align: 'center', width: '150', formatter: function (value, row, index) {
	            	return '<a style="word-wrap:break-word;">'+value+'</a>';
	            }},
	            {field: 'wetherPublish', title: '是否发布', align: 'center', width: '150', formatter: function (value, row, index) {
	            	if(value == 0){
	            		return '<a style="word-wrap:break-word;color:blue">未发布</a>';
	            	}else if(value == 1){
	            		return '<a style="word-wrap:break-word;color:green">已发布</a>';
	            	}else if(value == 2){
	            		return '<a style="word-wrap:break-word;color:red">取消发布</a>';
	            	}
	            }},
	            {field: 'publishUser', title: '发布人', align: 'center', width: '150', formatter: function (value, row, index) {
	            	if(isNull(value)){
	            		value = '-';
	            	}
	            	return '<a style="word-wrap:break-word;">'+value+'</a>';
	            }},
	            {field: 'publishTime', title: '发布时间', align: 'center', width: '150', formatter: function (value, row, index) {
	            	if(value == ''||value == null){
	            		value = '-';
	            	}
	            	return '<a style="word-wrap:break-word;">'+value+'</a>';
	            }},
	            {field: 'menuVersion', title: '菜单版本', align: 'center', width: '150', formatter: function (value, row, index) {
	            	return '<a style="word-wrap:break-word;">'+value+'</a>';
	            }},
	            {field: 'wetherUser', title: '是否使用', align: 'center', width: '150', formatter: function (value, row, index) {
	            	if(value == 0){
	            		return '<a style="word-wrap:break-word;color:red">未使用</a>';
	            	}else if(value == 1){
	            		return '<a style="word-wrap:break-word;color:green">使用中</a>';
	            	}
	            	return '<a style="word-wrap:break-word;">'+value+'</a>';
	            }},
	            {field: 'operate', 
	            	title: '操作', 
	            	align: 'center', 
	            	width: '300', 
	            	events: {
	            		 //删除
	            		'click .RoleOfA': function (e, value, row, index) {
	            	        qiao.bs.confirm("确定要删除此项吗？",function(){
	            	        	deleteWechat_Menu(row.id);
	            	        },function(){});
	            	    },
	            	    //查看详情
	            	    'click .RoleOfB': function (e, value, row, index) {
	            	    	menuVersion = row.menuVersion;
	            	    	var params = { 
	            					menuVersion:menuVersion,
	            					menuGrade:1
	            				};
	            			AjaxPostUtil.request({url:path+"9e9cd74aec0546acbc8165681dc7c3fd" ,params:params,type:'json',callback:function(jsonMation){
	            				if(jsonMation.returnCode==0){
	            					console.log(jsonMation);
	            					var source = $("#menuListBean").html();  
	            					var template = Handlebars.compile(source);
	            					$("#menuNameInfoDiv").html(template(jsonMation));
	            					countMenuWidth();
	            					$('#queryWechatMenuModal').modal('show');
	            				}
	            			}});
	            	    },
	            	    //编辑
	            	    'click .RoleOfC': function (e, value, row, index) {
	            	    	menuVersion = row.menuVersion;
	            	    	getMenuVersion(menuVersion);
	            	    	$("#addWechatMenuModal").modal("show");
	            	    	
	            	    },
	            	    //改变发布状态
	            	    'click .RoleOfD': function (e, value, row, index) {
	            	    	var wetherUser=wetherPublish=null;
	            	    	if(row.wetherUser == 0){//未使用
	            	    		wetherUser = 1;
	            	    		wetherPublish = 1;
	            	    	}else{//使用中
	            	    		wetherUser = 0;
	            	    		wetherPublish = 2;
	            	    	}
	            	    	var params={
	            					id:row.id,
	            					menuVersion:row.menuVersion,
	            					wetherUser:wetherUser,
	            					wetherPublish:wetherPublish
	            			}
	            	    	AjaxPostUtil.request({url:path+"2c5a6ff211f146a9aabda950fdbe53c7",params:params,type:'json',callback:function(json){
	            				if(json.returnCode == 0){
	            					qiao.bs.msg({msg:json.returnMessage+"，菜单改变后，将在24小时内生效！",type:'success'});
	            					$('#messageTable').bootstrapTable('refresh',{url:path+'408d41b977294903a85e815bb32bbdaa'});
	            				}else{
	            					qiao.bs.msg({msg:json.returnMessage,type:'danger'});
	            				}
	            			}
	            			});
	            	    },
	            	},
	            	formatter: function (value, row, index) {
	            		var str = "";
	            		if (row.wetherPublish == 1){
	            			str = [
	            					'<button type="button" class="RoleOfB btn btn-default  btn-sm" style="margin-right:15px;">详情</button>',
	            			        '<button type="button" class="RoleOfA btn btn-default  btn-sm" style="margin-right:15px;">删除</button>',
	            					'<button type="button" class="RoleOfD btn btn-default  btn-sm" style="margin-right:15px;">取消发布</button>', 
	            					]
	            		}else{
	            			str = [
	            				'<button type="button" class="RoleOfB btn btn-default  btn-sm" style="margin-right:15px;">详情</button>',
	            		        '<button type="button" class="RoleOfA btn btn-default  btn-sm" style="margin-right:15px;">删除</button>',
	            		        '<button type="button" class="RoleOfC btn btn-default  btn-sm" style="margin-right:15px;">编辑</button>',
	            				'<button type="button" class="RoleOfD btn btn-default  btn-sm" style="margin-right:15px;">发布</button>', 
	            			  ]
	            		}
	            			
	            		return str.join('');
	            	}
	            }
	    ],
        onLoadSuccess: function(data){  //加载成功时执行
        	if(data.returnCode!=0){
        		qiao.bs.msg({msg:data.returnMessage,type:'danger'});
        	}
        }
    });
}

//获取菜单版本号，并计算“+”号的大小
function getMenuVersion(menuVersion){
	
	 //版本号为空获取版本号，否则直接查询版本下所有菜单
	if(menuVersion == null || menuVersion == ''){
		AjaxPostUtil.request({url:path+"b8e449806edd43fba7553444ac8e6dbd",params:{},type:'json',callback:function(json){
			if(json.returnCode==0){
				window.newVersion = json.bean.menuVersion;//newVersion属于全局变量
			}
		}});
		loadMenuMation();
	}else{//查找本版本号下所有一级菜单,在serviceImpl层有查二级菜单
		var params = { 
				menuVersion : menuVersion,
				menuGrade : 1
		};
		AjaxPostUtil.request({url:path+"9e9cd74aec0546acbc8165681dc7c3fd",params:params,type:'json',callback:function(jsonMation){
			if(jsonMation.returnCode==0){
				console.log(jsonMation);
				var source = $("#menuListBean").html();  
			    var template = Handlebars.compile(source);
			    $("#menuNameDiv").html(template(jsonMation));
			    loadMenuMation();
			}
		}});
	}
	
}

function eventInit(){
	
	//关闭（X)按钮 closeQueryBtn
	$('body').on('click', '#closeBtn', function(){
		location.reload();//刷新当前页面，防止menuVersion缓存影响菜单获取 
	});
	//新增按钮。打开新增的模态框
	$('body').on('click', '#addWechatMenu', function(){
		//获取菜单版本号以及“+”的添加
		getMenuVersion(menuVersion);
		
		//打开增加菜单的模态框
		$("#addWechatMenuModal").modal("show");
		
	});
	
	$('body').on('click', '.menu', function(e){
		
		if ($(this).hasClass("cura")) {
			$(this).children(".new-sub").hide(); //当前菜单下的二级菜单隐藏
			$(".menu").removeClass("cura"); //同一级的菜单项
		} else {
			$(".menu").removeClass("cura"); //移除所有的样式
			$(this).addClass("cura"); //给当前菜单添加特定样式
			$(".menu").children(".new-sub").slideUp("fast"); //隐藏所有的二级菜单
			$(this).children(".new-sub").slideDown("fast"); //展示当前的二级菜单
		}
		//触发添加键
		if($(this).children("div").hasClass("firstAddMenu")){
			$('#menuName').val("");
			$('#rebackContext').val("");
			$("#linkNet").val("");
			var params={
				menuName:"一级菜单",
				menuVersion:window.newVersion,
				menuGrade:1,
				rebackInt:0
			}
			//添加一级菜单
			AjaxPostUtil.request({url:path+"f8e2bab28b9340c2b6f067f4925c7975",params:params,type:'json',callback:function(json){
				if(json.returnCode==0){
					menuVersion = window.newVersion;
					getMenuVersion(menuVersion);
				}
			}},true);
		}else{//点击的是其他菜单项
			$("#footerModal").show();
			var	params={
				id:$(this).children(".bt-name").attr("rowId")
			};
			//获取本菜单项id，将该菜单内容展示出来
			AjaxPostUtil.request({url:path+"811396a1141a493fa4d78ecb655fbc54",params:params,type:'json',callback:function(jsonMation){
				if(jsonMation.returnCode==0){
					$('#menuName').val(jsonMation.bean.menuName);
					$("#menuName").attr("menuId", jsonMation.bean.id);
					menuId=jsonMation.bean.id;
					$("#menuName").attr("grade", jsonMation.bean.menuGrade);
					if(jsonMation.bean.hasChild==1){
						$("#myTabContent").hide();
					}else{
						$("#myTabContent").show();
					}
					if(jsonMation.bean.rebackInt!=6){
						if(jsonMation.bean.rebackInt==0){
							$("#myTab").children("li:eq("+0+")").addClass("active");
							$("#myTab").children("li:eq("+1+")").removeClass("active");
							$("#ios").attr("class","tab-pane fade margin-Top-Left-30");
							$("#home").attr("class","tab-pane fade  in active");
							$("#Tw").children("li").removeClass("active");
							$("#Tw").children("li:eq("+0+")").addClass("active");
							$("#context").children("div").attr("class","tab-pane fade");
							$("#context").children("div:eq("+0+")").attr("class","tab-pane fade  in active");
							
						}else{
							$("#myTab").children("li:eq("+0+")").addClass("active");
							$("#myTab").children("li:eq("+1+")").removeClass("active");
							$("#ios").attr("class","tab-pane fade margin-Top-Left-30");
							$("#home").attr("class","tab-pane fade  in active");
							$("#Tw").children("li").removeClass("active");
							$("#Tw").children("li:eq("+(jsonMation.bean.rebackInt-1)+")").addClass("active");
							$("#context").children("div").attr("class","tab-pane fade");
							$("#context").children("div:eq("+(jsonMation.bean.rebackInt-1)+")").attr("class","tab-pane fade  in active");
							if(jsonMation.bean.rebackInt==5){
								$('#rebackContext').val(jsonMation.bean.rebackContext);
							}
						}
					}else {
						$("#myTab").children("li:eq("+0+")").removeClass("active");
						$("#myTab").children("li:eq("+1+")").addClass("active");
						$("#ios").attr("class","tab-pane fade margin-Top-Left-30 in active");
						$("#home").attr("class","tab-pane fade");
						$("#linkNet").val(jsonMation.bean.rebackContext);
					}
				}
			}});
		}
	});
	
	//二级菜单触发
	$('body').on('click', '.rowMenu', function(e){
		//触发二级菜单添加键
		if($(this).hasClass("addSecondMenu")){
			$('#menuName').val("");
			$('#rebackContext').val("");
			$("#linkNet").val("");
			var beanParams={
				menuName:"二级菜单",
				menuVersion:menuVersion,
				menuGrade:2,
				menuBelong:$(this).parent().parent().parent().children(".bt-name").attr("rowId"),
				rebackInt:0
			}
			//添加二级菜单
			AjaxPostUtil.request({url:path+"69bb6406af6341a390de992089241bc3",params:beanParams,type:'json',callback:function(json){
				if(json.returnCode==0){
					getMenuVersion(menuVersion);
				}
			}});
			e.stopPropagation();
		}else{
			$("#myTabContent").show();
			$("#footerModal").show();
				var	params={
						id:$(this).attr("rowId")
				};
				AjaxPostUtil.request({url:path+"811396a1141a493fa4d78ecb655fbc54",params:params,type:'json',callback:function(jsonMation){
					if(jsonMation.returnCode==0){
						$('#menuName').val(jsonMation.bean.menuName);
						$("#menuName").attr("menuId", jsonMation.bean.id);
						menuId=jsonMation.bean.id;
						$("#menuName").attr("grade", jsonMation.bean.menuGrade);
						if(jsonMation.bean.rebackInt!=6){
							if(jsonMation.bean.rebackInt==0){
								$("#myTab").children("li:eq("+0+")").addClass("active");
								$("#myTab").children("li:eq("+1+")").removeClass("active");
								$("#ios").attr("class","tab-pane fade margin-Top-Left-30");
								$("#home").attr("class","tab-pane fade  in active");
								$("#Tw").children("li").removeClass("active");
								$("#Tw").children("li:eq("+0+")").addClass("active");
								$("#context").children("div").attr("class","tab-pane fade");
								$("#context").children("div:eq("+0+")").attr("class","tab-pane fade  in active");
								
							}else{
								$("#myTab").children("li:eq("+0+")").addClass("active");
								$("#myTab").children("li:eq("+1+")").removeClass("active");
								$("#ios").attr("class","tab-pane fade margin-Top-Left-30");
								$("#home").attr("class","tab-pane fade  in active");
								$("#Tw").children("li").removeClass("active");
								$("#Tw").children("li:eq("+(jsonMation.bean.rebackInt-1)+")").addClass("active");
								$("#context").children("div").attr("class","tab-pane fade");
								$("#context").children("div:eq("+(json.bean.rebackInt-1)+")").attr("class","tab-pane fade  in active");
								if(jsonMation.bean.rebackInt==5){
									$('#rebackContext').val(jsonMation.bean.rebackContext);
									}
								}
							
							}else {
								$("#myTab").children("li:eq("+0+")").removeClass("active");
								$("#myTab").children("li:eq("+1+")").addClass("active");
								$("#ios").attr("class","tab-pane fade margin-Top-Left-30 in active");
								$("#home").attr("class","tab-pane fade");
								$("#linkNet").val(jsonMation.bean.rebackContext);
								}
						}
					}},true);
				e.stopPropagation();
				}
		});
	
	
	//保存按钮触发事件
	$('body').on('click','#saveBean',function(e){
	    if(isNull($("#menuName").val())){
			qiao.bs.msg({msg:"菜单名称不能为空",type:'danger'});
			return;
		} else if($("#menuName").attr("grade")==1&&$("#menuName").val().length>4){
			qiao.bs.msg({msg:"一级菜单不能超过四个字",type:'danger'});
			return;
		}else if($("#menuName").attr("grade")==2&&$("#menuName").val().length>6) {
			qiao.bs.msg({msg:"二级菜单不能超过六个字",type:'danger'});
			return;
		}else{
			//对回复内容的选择进行判断并存储
			for(var i = 0;i<5;i++){
				//如果选择的是跳转网页，判断链接是否合法，合法存储，不合法给出提示
				if($("#ios").hasClass("active")){
					if(IsURL($("#linkNet").val())){
						  rebackInt=6;
						  rebackContext=$("#linkNet").val();
						  break;
					  }else{
						  qiao.bs.msg({msg:"输入的网址不正确，请重新输入",type:'danger'});
					      return;
					  }
				  }
				//如果选择的是发送消息，依次判断选择的是那个选卡，如果选择的是文字（4）需判断回复内容是否为空，其他选卡内容直接存储
				if($("#Tw").children("li:eq("+i+")").hasClass("active")){
					rebackInt=i+1;
					if(i!=4){
					rebackContext= $("#context").children("div:eq("+i+")").text();
					}else{
						if(isNull($('#rebackContext').val())){
							qiao.bs.msg({msg:"回复内容不能为空",type:'danger'});
							return;
						}else{
							rebackContext=$('#rebackContext').val();  
							}
						}
					}
			}
			//存储更改后的信息
			var params={
				id:$("#menuName").attr("menuId"),
				menuName:$("#menuName").val(),
				rebackContext:encodeURIComponent(rebackContext),
				rebackInt:rebackInt,
			}
			AjaxPostUtil.request({url:path+"142e1f255e8f4c3483cdfee46f503f3d",params:params,type:'json',callback:function(json){
				if(json.returnCode==0){
					qiao.bs.msg({msg:json.returnMessage,type:'success'});
					//将该版本的菜单设置为未发布状态
					var publishparam={
							menuVersion:menuVersion,
							wetherUser:0,
							wetherPublish:0
					}
				    AjaxPostUtil.request({url:path+"2c5a6ff211f146a9aabda950fdbe53c7",params:publishparam,type:'json',callback:function(jsonMation){
						if(jsonMation.returnCode == 0){
							qiao.bs.msg({msg:jsonMation.returnMessage,type:'success'});
						}else{
							qiao.bs.msg({msg:jsonMation.returnMessage,type:'danger'});
						}
					}
					});
					getMenuVersion(menuVersion);
				}
			}},true);
			}
	}); 
	
	//模态框中删除二级子菜单
	$('body').on('click','#deleteBean',function(e){
		qiao.bs.confirm("是否删除该项菜单？",function(){
		var params = {
				id:$("#menuName").attr("menuId")
		}
		AjaxPostUtil.request({url:path+"4351f50cf1ab42d683dea9a2de933ced",params:params,type:'json',callback:function(json){
			if(json.returnCode==0){
				qiao.bs.msg({msg:json.returnMessage,type:'success'});
				//将改菜单更改为未发布状态
				var publishparam={
						menuVersion:menuVersion,
						wetherUser:0,
						wetherPublish:0
			         }
			    AjaxPostUtil.request({url:path+"2c5a6ff211f146a9aabda950fdbe53c7",params:publishparam,type:'json',callback:function(jsonMation){
					if(jsonMation.returnCode == 0){
						qiao.bs.msg({msg:jsonMation.returnMessage,type:'success'});
					}else{
						qiao.bs.msg({msg:jsonMation.returnMessage,type:'danger'});
					}
				}
				});
				getMenuVersion(menuVersion);//重新加载本版本下的菜单
				//将页面设置为发送消息图文消息显示的状态
				$("#myTab").children("li:eq("+0+")").addClass("active");
				$("#myTab").children("li:eq("+1+")").removeClass("active");
				$("#ios").attr("class","tab-pane fade margin-Top-Left-30");
				$("#home").attr("class","tab-pane fade  in active");
				$("#Tw").children("li").removeClass("active");
				$("#Tw").children("li:eq("+0+")").addClass("active");
				$("#context").children("div").attr("class","tab-pane fade");
				$("#context").children("div:eq("+0+")").attr("class","tab-pane fade  in active");
				$('#rolePrompt').val("");
				$('#menuName').val("");
			}else{
				qiao.bs.msg({msg:json.returnMessage,type:'danger'});
			}
		}});
		},function(){});
	});
	
	//刷新表单
	$('body').on('click', '#refreshDiv', function(e){
		$('#messageTable').bootstrapTable('refresh',{url : path+'408d41b977294903a85e815bb32bbdaa'});
		qiao.bs.msg({msg : "刷新成功.", type : 'success'});
	});
}

//刷新菜单
function loadMenuMation(){
	strAdd = '<div class="menu"><div class="bt-name firstAddMenu"><img src="../../assets/images/tianjia.png" class="addMenuPng"/></div></div>';
	strBeanAdd = '<li class="rowMenu addSecondMenu"><a href="javascript:;"><img src="../../assets/images/tianjia.png" class="addMenuPng"/></a></li>';
	var menuFirst = $(".menu");
	//为以一级菜单添加
	if(menuFirst.length<3){
		$("#menuNameDiv").html($("#menuNameDiv").html() + strAdd);
		countMenuWidth();
	}
	//为二级菜单添加
	$(".menu").each(function(){
    	if($(this).children(".new-sub").children("ul").children("li") .length<5){
    		$(this).children(".new-sub").children("ul").html(strBeanAdd + $(this).children(".new-sub").children("ul").html());
    	}
    });
	countMenuWidth();//计算显示样式
}

//计算图片“+”的大小
function countMenuWidth(){
	
	var menu = $(".menu");
	if(menu.length==1){
		$(".menu").css("width","100%");
	}else if(menu.length==2){
		$(".menu").css("width","50%");
	}else if(menu.length==3){
		$(".menu").css("width","33%");
	}
}

//验证链接是否合法
function IsURL(str){
	return !!str.match(/^(http|https):\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/);
}

//删除一级菜单（联动删除相应的二级菜单）
function deleteWechat_Menu(rowId){
	var params = {
			rowId:rowId,
			menuBelong : rowId
	}
	AjaxPostUtil.request({url : path+"788fadd274c545ca8c51cfc6bd54dbcf", params : params, type : 'json', callback : function(jsonMation){
		if(jsonMation.returnCode == 0){
			qiao.bs.msg({msg : "删除成功.", type : 'success'});
			$('#messageTable').bootstrapTable('refresh',{url : path+'408d41b977294903a85e815bb32bbdaa'});
		}else{
			qiao.bs.msg({msg : "参数错误.", type : 'danger'});
		}
	}});
}

